package com.fmy.security.service.login;

import com.fmy.security.service.login.authenticator.CustAuthenticator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.List;

/**
 * @author Mr.fmy
 * @version 1.0.0
 * @ClassName CustUserNameService
 * @Description TODO 自定义UserDetailsService实现类、如果需要扩展登录、可以配置该实现方式/否则按正常即可
 * @createTime 2019/9/10 11:08
 */
public class CustUserDetailsService implements UserDetailsService {

    private List<CustAuthenticator> authenticators;

    @Autowired(required = false)
    public void setAuthenticators(List<CustAuthenticator> authenticators) {
        this.authenticators = authenticators;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        CustAuthentication authentication = CustAuthenticationHolder.get();
        //判断是否是集成登录
        if (authentication == null) {
            authentication = new CustAuthentication();
        }
        authentication.setUsername(username);
        return authenticate(authentication);
    }

    private UserDetails authenticate(CustAuthentication authentication) {
        if (this.authenticators == null || this.authenticators.size() == 0) {
            throw new IllegalArgumentException("必须保证至少存在一个 CustAuthenticator 的实现接口");
        }
        for (CustAuthenticator authenticator : authenticators) {
            if (authenticator.support(authentication)) {
                return authenticator.authenticate(authentication);
            }
        }
        throw new IllegalArgumentException(authentication.getAuthType()+" 类型登录方式、未找到认证 Authentication");
    }
}
